package utils

/**
golan 数据库访问框架，测试用例，文档参考http://xorm.io/docs/
*/
import (
	// "fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	// "testing"
)

type XormTrans struct {
	xormEngine  *xorm.Engine
	xormSession *xorm.Session
}

func NewXormEngine() (engine *xorm.Engine) {
	if conf.Mysql.User == "" {
		panic("数据库用户名配置有误！")
	}
	if conf.Mysql.Pswd == "" {
		panic("数据库密码配置有误！")
	}
	if conf.Mysql.Database == "" {
		panic("数据库名称配置有误！")
	}
	if conf.Mysql.Charset == "" {
		conf.Mysql.Charset = "utf8mb4"
	}
	if conf.Mysql.Host == "" {
		conf.Mysql.Host = "127.0.0.1"
	}
	if conf.Mysql.Port == "" {
		conf.Mysql.Port = "3306"
	}

	sqlDsn := conf.Mysql.User + ":" + conf.Mysql.Pswd + "@tcp(" + conf.Mysql.Host + ":" + conf.Mysql.Port + ")/" + conf.Mysql.Database + "?charset=" + conf.Mysql.Charset
	engine, err := xorm.NewEngine("mysql", sqlDsn)
	if err != nil {
		panic("数据库连接错误！")
	}

	if conf.Log.Debug == 1 {
		engine.ShowSQL(true)
	}

	return engine
}

//生成数据连接
func NewXormTrans() *XormTrans {

	xt := new(XormTrans)

	if xt.xormEngine != nil {
	} else {
		xt.xormEngine = NewXormEngine()
	}
	session := xt.xormEngine.NewSession()
	xt.xormSession = session
	return xt
}

//获得当前会话
func (xt *XormTrans) GetCurrentXormSession() (session *xorm.Session) {
	return xt.xormSession
}

//获得当前xormengine
func (xt *XormTrans) GetCurrentXormEngine() (session *xorm.Engine) {
	return xt.xormEngine
}

func (xt *XormTrans) NewBegin() {
	xt.xormSession.Close()
	xt.xormSession.Init()
	err := xt.xormSession.Begin()
	if err != nil {
		xt.xormSession.Rollback()
		xt.xormSession.Close()
		panic(err)
	}
}

func (xt *XormTrans) Rollback() {
	xt.xormSession.Rollback()
}

func (xt *XormTrans) Commit() {
	xt.xormSession.Commit()
}

func (xt *XormTrans) CloseSession() {
	xt.xormSession.Close()
}
